# -*- coding: utf-8 -*-

# Create your views here.
from captcha.client import displayhtml
from datetime import datetime
from django.db.models.query_utils import Q
from django.http import Http404, HttpResponseNotFound
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.views.decorators.csrf import ensure_csrf_cookie
from events.ajax import check_signup_captcha
from events.models import Event, Participant
from events.response import CSVResponse
from index import needAuthForm
from users.models import UserProfile
import settings

def checkEventSignupDateTime(e, todayDateTime):
    signupExpired = False
    signupAheadof = False
    signupOnGoing = False
    
    if e.signupEndDateTime != None and todayDateTime > e.signupEndDateTime:
        signupExpired = True
    elif e.signupStartDateTime != None and todayDateTime < e.signupStartDateTime:
        signupAheadof = True
    else:
        signupOnGoing = True
    return signupExpired, signupAheadof, signupOnGoing

def eventMain(request):
    # get recent events : event_recent_list
    # get expired events : event_expired_list
    recent_list = Event.objects.all().order_by('date')
    record_list = Event.objects.all().order_by('-date')
    return render_to_response('template_EventMain.html',
                              needAuthForm({
                                            'event_recent_list': recent_list,
                                            'event_record_list': record_list,
                                            'todayDateTime' : datetime.today(),
                                             }),
                              context_instance=RequestContext(request)
                              )

def eventDescript(request, event_id):
    e = get_object_or_404(Event, pk=event_id)
    today = datetime.today()
    signupExpired, signupAheadof, signupOnGoing = checkEventSignupDateTime(e, today)
    
    hasRecord = False
    if e.date != None and today > e.date:
        hasRecord = True
        
    return render_to_response('template_EventDescript.html',
                               needAuthForm({'event':e ,
                                             'signupExpired': signupExpired,
                                             'signupAheadof': signupAheadof,
                                             'signupOnGoing': signupOnGoing,
                                             'hasRecord': hasRecord,
                                             }),
                               context_instance=RequestContext(request))

def eventResult(request, event_id):
    e = get_object_or_404(Event, pk=event_id)
    allList = e.participant_set.values('name', 'serial', 'record', 'totalRank')
    if allList is not None:
        rankList = allList.exclude( Q(totalRank__isnull=True) | Q(totalRank__lte=0) )
        rankList = rankList.order_by('totalRank')
        dnfList = allList.filter( Q(totalRank__isnull=True) | Q(totalRank__lte=0) )
    
    return render_to_response('template_EventResult.html',
                               needAuthForm({'event':e ,
                                             'rankList':rankList,
                                             'dnfList':dnfList}),
                               context_instance=RequestContext(request))

@ensure_csrf_cookie
def signupMain(request, event_id):
    if request.method != 'POST':
        e = get_object_or_404(Event, pk=event_id)
        
        public_key = settings.RECAPTCHA_PUBLIC_KEY
        recaptcha_script = displayhtml(public_key=public_key, attrs={'theme' : 'clean'})
        
        signupExpired, signupAheadof, signupOnGoing = checkEventSignupDateTime(e, datetime.today())
        
        userHasProfile = False
        if not request.user.is_anonymous():
            try:
                pf = request.user.userprofile
                userHasProfile = pf.modified > 0
            except (UserProfile.DoesNotExist):
                userHasProfile = False
            
        # sign up page need not auth form
        return render_to_response('template_EventSignup.html',
                                  {
                                   'auth_block': True,
                                   'event':e ,
                                   'recaptcha_widget_signup':recaptcha_script,
                                   'signupExpired': signupExpired,
                                   'signupAheadof': signupAheadof,
                                   'signupOnGoing': signupOnGoing,
                                   'userHasProfile':userHasProfile,
                                   },
                                  context_instance=RequestContext(request)
                                  )
        
def signupSucceed(request, event_id, signupkey):
    try:
        pdata = Participant.objects.get(signupKey=signupkey)        
        return render_to_response('template_EventSignupSucceed.html',
                                  needAuthForm({
                                                'event':pdata.event,
                                                'pData':pdata,
                                                }
                                               ),
                                  context_instance=RequestContext(request)
                                  )
    except (Participant.DoesNotExist, Participant.MultipleObjectsReturned):
        raise Http404

@ensure_csrf_cookie
def signupModify(request, event_id, signupkey):
    try:
        event = Event.objects.get(pk=event_id)
    except Event.DoesNotExist:
        raise Http404
        
    errCode = None
    
    try:
        pdata = Participant.objects.get(signupKey=signupkey)
    except (Participant.DoesNotExist, Participant.MultipleObjectsReturned):
        errCode = 'InvalidSignupKey'
        return render_to_response('template_EventSignupModify.html',
                                  {
                                   'auth_block': True,
                                   'event':event,
                                   'errCode':errCode,
                                   },
                                  context_instance=RequestContext(request)
                                  )
    
    signupExpired, signupAheadof, signupOnGoing = checkEventSignupDateTime(event, datetime.today())
    public_key = settings.RECAPTCHA_PUBLIC_KEY
    recaptcha_script = displayhtml(public_key=public_key, attrs={'theme' : 'clean'})
    
    
    
    if signupExpired:
        errCode = 'signupExpired'
    if pdata.event.id != int(event_id):
        errCode = 'InvalidSignupKey'
    
    modifySucceed = False
    redirectResult = request.GET.get('r')
    if redirectResult == 'succeed':
        modifySucceed = True
        
    return render_to_response('template_EventSignupModify.html',
                              #needAuthForm(),
                              {
                               'auth_block': True,
                               'event':event,
                               'pData':pdata,
                               'errCode':errCode,
                               'modifySucceed':modifySucceed,
                               'recaptcha_widget_signup':recaptcha_script,
                               'signupExpired': signupExpired,
                               'signupAheadof': signupAheadof,
                               'signupOnGoing': signupOnGoing,
                               },
                              context_instance=RequestContext(request)
                              )
    
def signupDisclaimer(request, event_id):
    try:
        event = Event.objects.get(pk=event_id)
    except Event.DoesNotExist:
        raise Http404
    return render_to_response('template_EventDisclaimer.html',
                              needAuthForm({
                                            'event':event,
                                            }),
                              context_instance=RequestContext(request)
                              )
    

def exportData(request):
    user = request.user
    if user is None:
        raise Http404
    if not user.is_staff:
        raise Http404
    
    event_id = 0
    event_columns = []
    parti_columns = []
    
    postDict = dict(request.POST)
    for k in postDict :
        if k.startswith('eventinfoKeys_id'):
            event_columns = postDict[k][0].split('_')
        elif k.startswith('participantKeys_id'):
            parti_columns = postDict[k][0].split('_')
        elif k == 'event_id':
            event_id = int(postDict[k][0])
    
    return CSVResponse(event_id, event_columns, parti_columns)
